# mg = makeGrass

from googletrans import Translator
import os
import re
import sys
from pdfdocx import read_pdf

trans_dir = "D:\\Trans\\"
txt_dir = "D:\\Trans\\dai"
def cn2en(source):
        translator = Translator(service_urls=['translate.google.cn'])
        #print(source)
        text = translator.translate(source,src='zh-cn',dest='en').text
        return text

def en2cn(source):
        translator = Translator(service_urls=['translate.google.cn'])
        #print(source)
        if source:
                text = translator.translate(source,src='en',dest='zh-cn')
                if text:
                    return text.text

def makeGrass(text,times=1):
        for i in range(times):
                temp = en2cn(text)
        #print(temp)
        if temp:
            return temp

def listdir_rel(path, list_name):  #传入存储的list
    for file in os.listdir(path):  
        file_path = file  
        if os.path.isdir(file_path):  
            print(file_path) 
        else:  
            list_name.append(file_path)
            
def listdir(path, list_name):  #传入存储的list
    for file in os.listdir(path):  
        file_path = os.path.join(path, file)  
        if os.path.isdir(file_path):  
            print(file_path) 
        else:  
            list_name.append(file_path)
def is_ascii(s):
    return all(ord(c) < 128 for c in s)


file_list = []
listdir(trans_dir, file_list)
for i in file_list:
        print(i)
        out_file = open(i+"_cn.txt", "w", encoding='UTF-8')
        in_file = open(i, "r", encoding='UTF-8')
        cnt = 0
        for strn in in_file.readlines():
##                print("cnt" +str(cnt))
##                cnt = cnt + 1
##                print("len:" +str(len(strn)))
                if len(strn.strip()) > 5 and is_ascii(strn):
                        if '.' in strn:
                                text = makeGrass(strn.strip().replace(".", ""))
                        else:
                                text = makeGrass(strn.strip())
                else:
                        text = None
                if text:
                        out_file.write(text)
                        out_file.write("\n")

        in_file.close()
        out_file.close()

